import React, { useEffect, useState, useRef, useCallback } from "react";
import style from "./index.module.css";
import { SearchOutline, SoundOutline } from "antd-mobile-icons";
import { request } from "../axios/request";
import { Button, SpinLoading } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { checkAuth, getUserPhone } from "../utils/auth";

function Index() {
  const [doctorlist, setDoctorlist] = useState([]);
  const [pageCode, setPageCode] = useState(1);
  const [pageSize] = useState(10);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [total, setTotal] = useState(0);
  const [selectedAdmin, setSelectedAdmin] = useState('全部');
  const nav = useNavigate();
  const scrollRef = useRef(null);

  // 科室分类选项 - 对应admin参数
  const adminOptions = [
    { label: '全部', value: '全部' },
    { label: '妇产科', value: '妇产科' },
    { label: '儿科', value: '儿科' },
    { label: '皮肤科', value: '皮肤科' },
    { label: '心血管内科', value: '心血管内科' },
    { label: '呼吸内科', value: '呼吸内科' },
    { label: '神经内科', value: '神经内科' },
    { label: '消化内科', value: '消化内科' },
    { label: '骨科', value: '骨科' },
    { label: '眼科', value: '眼科' },
    { label: '耳鼻喉科', value: '耳鼻喉科' },
  ];

  // 检查登录状态
  useEffect(() => {
    if (!checkAuth(nav)) {
      return; // 如果未登录，checkAuth会自动跳转到登录页面
    }
    diaoyong();
  }, [nav]);

  const diaoyong = async (isLoadMore = false) => {
    try {
      setLoading(true);
      const res = await request.get("/doctor/list", {
        params: {
          pageCode: isLoadMore ? pageCode + 1 : 1,
          pageSize: pageSize,
          admin: selectedAdmin === '全部' ? '' : selectedAdmin
        }
      });
      
      if (res.data.code == 20000) {
        const newData = res.data.data;
        console.log('医生列表数据:', newData);
        
        // 处理返回数据，兼容不同格式
        let doctors = [];
        let totalCount = 0;
        
        if (Array.isArray(newData)) {
          doctors = newData;
          totalCount = newData.length;
        } else if (newData && Array.isArray(newData.records)) {
          doctors = newData.records;
          totalCount = Number(newData.total || newData.records.length || 0);
        }
        
        if (isLoadMore) {
          setDoctorlist(prev => [...prev, ...doctors]);
          setPageCode(prev => prev + 1);
        } else {
          setDoctorlist(doctors);
          setPageCode(1);
        }
        
        setTotal(totalCount);
        setHasMore(doctors.length === pageSize);
      }
    } catch (error) {
      console.error('获取医生列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const dianji = (id: string) => {
    console.log(id);
    nav(`/doctor/${id}`);
  };
  
  const sousuodianji = () => {
    nav("/sousuo");
  };

  // 滚动到底部加载更多
  const handleScroll = useCallback((e) => {
    const { scrollTop, scrollHeight, clientHeight } = e.target;
    const threshold = 50; // 距离底部50px时触发加载
    
    if (scrollHeight - scrollTop - clientHeight < threshold && !loading && hasMore) {
      diaoyong(true);
    }
  }, [loading, hasMore, pageCode, pageSize, selectedAdmin]);

  // 科室分类切换
  const handleAdminChange = (admin) => {
    setSelectedAdmin(admin);
    setPageCode(1);
    setHasMore(true);
    // 切换分类时重新加载数据
    setTimeout(() => {
      diaoyong(false);
    }, 0);
  };

  // 添加滚动监听
  useEffect(() => {
    const scrollElement = scrollRef.current;
    if (scrollElement) {
      scrollElement.addEventListener('scroll', handleScroll);
      return () => {
        scrollElement.removeEventListener('scroll', handleScroll);
      };
    }
  }, [handleScroll]);

  return (
    <div className={style.dabox}>
      <div className={style.dingbu}>
        <div>妙手医生·</div>
        <div style={{ marginLeft: "5px" }}>妙手互联网医院</div>
        {/* 显示当前登录用户 */}
        <div style={{ marginLeft: "auto", fontSize: "12px", color: "#666" }}>
          欢迎，{getUserPhone()}
        </div>
      </div>
      <div className={style.zhongjian} ref={scrollRef} style={{ overflowY: 'auto', height: 'calc(100vh - 120px)' }}>
        <div className={style.zhongyi}></div>
        <div className={style.zhonger} onClick={() => sousuodianji()}>
          <div>
            <span>
              <SearchOutline fontSize={20} />
            </span>
            <span>搜索医生、医院、药品、疾病症状等</span>
          </div>
        </div>
        <div className={style.zhongsan}>
          <div className={style.laba}>
            <SoundOutline fontSize={17} color="rgb(251, 138, 64)" />
          </div>
          <div className={style.neirong}>
            <div className={style.gundonga}>
              公告：今天医院内不接受任何患者 住院的患者同志
              可以在住院大厅的服务台领取两瓶"葡萄糖"!!!!
            </div>
          </div>
        </div>
        <div className={style.zhongsi}>
          <div>预约挂号</div>
          <div>极速问诊</div>
          <div>复诊开方</div>
        </div>
        
        {/* 科室分类选择器 */}
        <div className={style.departmentSelector}>
          <div className={style.departmentScroll}>
            {adminOptions.map((option) => (
              <div
                key={option.value}
                className={`${style.departmentItem} ${
                  selectedAdmin === option.value ? style.departmentActive : ''
                }`}
                onClick={() => handleAdminChange(option.value)}
              >
                {option.label}
              </div>
            ))}
          </div>
        </div>
        
        <div className={style.liebiao}>
          {doctorlist.map((i, index) => (
            <div className={style.doctor} key={i.doctorid || index}>
              <div className={style.toxiang}>
                <div className={style.img}>
                  {/* doctorimage */}
                  <img
                    style={{ width: "100%", height: "100%" }}
                    src={i.doctorimage}
                    alt=""
                  />
                </div>
              </div>
              <div className={style.neirong}>
                <div>
                  <span
                    style={{
                      fontSize: "20px",
                      fontWeight: 700,
                      marginRight: "10px",
                    }}
                  >
                    {i.doctorname}
                  </span>
                  <span>{i.doctorstate}</span>
                </div>
                <div>擅长：{i.socoadmin}</div>
                {/* socoadmin */}
                <div>医科；{i.socoadmin}</div>
                {/* sococity */}
                <div>医疗城市：{i.doctorcity}</div>
                {/* 资讯费用doctorprice */}
                <div className={style.zixun}>
                  <div className={style.one}>￥{i.doctorprice}起</div>
                  <div className={style.two}>
                    <Button color="primary" onClick={() => dianji(i.doctorid)}>
                      问医生
                    </Button>
                  </div>
                </div>
              </div>
            </div>
          ))}
          
          {/* 加载状态 */}
          {loading && (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <SpinLoading />
              <div style={{ marginTop: '10px', color: '#999' }}>加载中...</div>
            </div>
          )}
          
          {/* 没有更多数据 */}
          {!loading && !hasMore && doctorlist.length > 0 && (
            <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
              没有更多医生了
            </div>
          )}
        </div>
      </div>
      <div className={style.dibu}></div>
    </div>
  );
}

export default Index;
